import {
  Controller,
  Get,
  Res,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Sse,
  Query
} from '@nestjs/common';
import { ChatService } from './chat.service';
import { Response } from 'express';
import { CreateChatDto } from './dto/create-chat.dto';
import { UpdateChatDto } from './dto/update-chat.dto';
import {
  Observable,
  interval,
  map,
  Subject,
  takeUntil,
  from,
  generate,
} from 'rxjs';
import { Stream, pipeline } from 'stream';
import { Http2Stream } from 'http2';

@Controller('chat')
export class ChatController {
  private subject = new Subject<any>();
  constructor(private readonly chatService: ChatService) {}

  @Post('list')
  async list(@Body() listBookDto: any) {
    try {
      let data = await this.chatService.list();
      return {
        code: 0,
        msg: 'ok',
        data,
      };
    } catch (e) {
      //返回400状态码
      return {
        code: -1,
        msg: e.message,
      };
    }
  }

  @Post('tts')
  async tts(@Body() req: any) {
    try {
      // console.log(req.len)
      let data = await this.chatService.tts(req);
      if (!data) {
        throw new Error('服务器波动，请重试');
      }
      return {
        code: 0,
        msg: 'ok',
        data,
      };
    } catch (e) {
      console.log(e);
      //返回400状态码
      return {
        code: -1,
        msg: e.message,
      };
    }
  }

  @Post('text2audio')
  async text2audio(@Body() req: any) {
    try {
      let r = (await this.chatService.text2audio(req)) as any;
      //console.log(r)
      //console.log(r)
      // res.set({
      //   'Content-Type': 'audio/mp3',
      //   // 可以设置其他响应头，如'Content-Disposition'等
      // });
      // res.body = r.body
      // console.log(r)
      // return JSON.parse(r.Headers)
      //res.setHeader('Content-Type', 'audio/mp3');
      //res.setHeader('Content-Type', 'audio/mpeg');
      // res.setHeader('Content-Disposition', 'inline; filename="audio.mp3"');

      // // 发送 Base64 编码的音频数据
      // res.status(200).send(r);
      // r.pipe(res)
      // pipeline(
      //   r.body, // 这是从 axios 获取的流
      //   res,
      //   err => {
      //     if (err) {
      //       console.error('Streaming error:', err);
      //       // res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(err.message);
      //     }
      //   }
      // );
      // r.on('end', () => {
      //   res.end();
      // });
      //return
      return {
        code: 0,
        msg: 'ok',
        data: r,
      };
    } catch (e) {
      console.log(e)
      return {
        code: -1,
        msg: e.message,
      };
    }
  }

  @Post('chat_test')
  chat_test(@Body() req: any) {}

  //历史记录，key表示某轮会话,{msg:[],time:} msg表示历史记录,time表示最后一次更新的时间，2个小时不更新后会清除对应的记录
  messages = []

  // @Post('chat_stream')
  // @Get()
  @Sse('chat_stream')
  chat_stream(@Query() query: any, @Res() res: Response): any {
    //console.log(query.tex)
    if(!query.tex){
      const observable = new Observable((subscriber) => {
        subscriber.complete();
      });
      return observable
    }
    const asyncIterable = this.chatService.chat_stream(query,this.messages);
    if(this.messages.length >= 12){
      this.messages = [
        ...this.messages.slice(2,10),
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": query.tex
            }
          ]
        }
      ]
    }else{
      this.messages.push({
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": query.tex
          }
        ]
      })
    }
    
    const observable = new Observable((subscriber) => {
      const getV = async () => {
        let r = await asyncIterable;
        let str = ''
        for await (const chunk of r) {
          let v = chunk.choices[0].delta;
          if(v.content){
            str+= v.content
          }
          subscriber.next({ data: v });
        }
        if(this.messages.length >= 10){
          this.messages = [
            ...this.messages.slice(2,10),
            {
              "role": "assistant",
              "content": [
                {
                  "type": "text",
                  "text": str
                }
              ]
            }
          ]
        }else{
          this.messages.push({
            "role": "assistant",
            "content": [
              {
                "type": "text",
                "text": str
              }
            ]
          })
        }
        
        subscriber.complete();
      };
      getV();
    });
    // console.log('just before subscribe');
    // observable.subscribe({
    //   next(x) {
    //     console.log(x);
    //   },
    //   error(err) {
    //     console.error('something wrong occurred: ' + err);
    //   },
    //   complete() {
    //     console.log('done');
    //   },
    // });
    // console.log('just after subscribe');
    return observable;
  }

  @Post('chat')
  async chat(@Body() req: any) {
    try {
      let data = await this.chatService.chat(req);
      if (!data) {
        throw new Error('服务器波动，请重试');
      }
      await this.chatService.create({
        ...req,
        input: req.template,
        output: data,
      });
      return {
        code: 0,
        msg: 'ok',
        data,
      };
    } catch (e) {
      console.log(e);
      //返回400状态码
      return {
        code: -1,
        msg: e.message,
      };
    }
  }
}
